package com.algorithm;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;

@Slf4j
public class OrderDbComplex implements ComplexKeysShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<String> shardingValue) {
        log.info("所有的sharding列的值为:{}", JSON.toJSONString(shardingValue));

        //获取当前的表名
        String logicTableName = shardingValue.getLogicTableName();

        //获取请求参数
        Map<String, Collection<String>> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Collection<String> corpCollection = columnNameAndShardingValuesMap.get(Constants.corp_code);
        Collection<String> customerCollection = columnNameAndShardingValuesMap.get(Constants.customer_code);
        if(CollectionUtils.isEmpty(corpCollection) && CollectionUtils.isEmpty(customerCollection) ){
            return collection;
        }

        Optional<String> firstCorp = corpCollection.stream().findFirst();
        Optional<String> firstCustomer = customerCollection.stream().findFirst();
        String corpCode = firstCorp.isPresent()?firstCorp.get():"0";
        String customerCode = firstCustomer.isPresent()?firstCustomer.get():"0";
        int actualTableIndex = ShardingDbUtil.getActualTableIndex(corpCode, customerCode, Constants.db_num);


        for (Iterator<String> iterator = collection.iterator(); iterator.hasNext();) {
            String next = iterator.next();
            if((Constants.ds_+actualTableIndex).equals(next)) {
                collection.add(next);
            }
        }

        return collection;
    }


}
